package com.treasure.service.filter;

import com.alibaba.fastjson.JSON;
import com.treasure.service.annotation.NoLogin;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.enums.CodeEnum;
import com.treasure.service.third.utils.SessionKey;
import com.treasure.service.third.utils.TokenConfig;
import com.treasure.service.third.utils.UserToken;
import com.treasure.service.result.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* @Description:    java类作用描述
* @Author:         panxinwen
* @CreateDate:     2018/11/25 10:12
* @Version:        1.0
*/
@Component
public class AuthHandlerInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(AuthHandlerInterceptor.class);
//    private static final String key = "X-GFS";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj)
            throws Exception {

        String uri = request.getRequestURI();

        if (uri.contains("swagger") || uri.contains("api-docs")){
            return super.preHandle(request, response, obj);
        }

        logger.info("拦截器运行,请求的URI是==={} sessionid==={}", uri,TokenConfig.getAttribute(SessionKey.TOKEN));

//        String xgfs = request.getHeader(key);

        try {
            UserToken user = TokenConfig.getTokenByHeader();
            logger.info("拦截器获取到的用户信息=={}",JSON.toJSONString(user==null?"":user));
            boolean needLogin = true;
            // 如果标注了无需登录,则可以不用登陆了
            if(obj instanceof HandlerMethod){
                needLogin = ((HandlerMethod) obj).getMethodAnnotation(NoLogin.class) == null;
            }

            if (needLogin && (user == null || StringUtil.isEmpty(user.getUserId()))) {

                logger.info("未登录！");

                response.setContentType("text/html;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.println(JSON.toJSONString(new ResponseResult(CodeEnum.NOLOGIN)));
                out.close();

                return false;

            }
        } catch (IOException e) {
            logger.error("出错了-----",e);
            return false;
        }
        return super.preHandle(request, response, obj);
    }

}
